/*
 * 布局通用逻辑
 * @params {
 *  props:{
 *    menuList, // 菜单列表
 *    menuTheme, // 菜单主题
 *    logo,
 *    header, // 头部
 *    footer, // 底部
 *    titleStyle, // 标题
 *    routerPushKey, // 路由跳转的key
 *    menuExpandedKeysHot, // 展开的key
 *    defaultSelectedKeysHot // 默认选中的key
 *  }
 * }
 */
import { computed, ref, watch, onMounted } from 'vue'
import { isEmpty,isArray } from '@/utils/is'
import LogoUrl from '@/assets/images/ai-logo-icon.png'
import { useUserStoreWithOut } from '@/store/modules/user'
import pageRouter from '@/router/routes/modules/dpaRouter'
import mainRouter from '@/router/routes/modules/router'
// @ts-ignore
const useAlLayoutEffect = function (props, extra = {} as any) {
    // ----------------------------------------- 属性
    const { routerPath } = extra || {}
    // 文字方向
    const alignType = {
        ALIGN_LEFT: 'left',
        ALIGN_CENTER: 'center',
        ALIGN_RIGHT: 'right'
    }
    // 展开
    const collapsed = ref(false)
    // 混合导航 控制tab选中下标
    const activeTab = ref<string>('')
    // 头部高度
    const headerHeight = 64
    // 展开的key
    const menuExpandedKeys = ref(props.menuExpandedKeysHot)
    // 默认展开的key
    const defaultSelectedKeys = ref(props.defaultSelectedKeysHot)
    // 默认logo
    const Logo = LogoUrl
    // ----------------------------------------- 监听
    watch(
        () => props.menuExpandedKeysHot,
        value => {
            menuExpandedKeys.value = value
        },
        {
            deep: true
        }
    )
    watch(
        () => props.menuList,
        value => {
            if (value) {
                handleDealMenuHightLight()
            }
        },
        {
            deep: true
        }
    )
    // ----------------------------------------- 计算属性
    // 混合模式tab的样式
    const tabsStyle = computed(() => {
        return {
            height: `${headerHeight}px`
        }
    })
    const tabStyle = computed(() => {
        const paddingHeight = 24
        const height = headerHeight - paddingHeight
        return {
            height: `${height}px`,
            display: `inline-block`,
            lineHeight: `${height}px`,
            position: 'relative'
        }
    })
    // layout menu 不支持custom参数
    const computedTheme = computed(() => {
        return props.menuTheme === 'custom' ? 'dark' : props.menuTheme
    })
    // 顶部导航布局和其他布局不一样 如果为浅色布局 mode则为linght
    const computedHorizontalTheme = computed(() => {
        if (['dark', 'custom'].includes(props.menuTheme)) {
            return 'dark'
        }
        return 'light'
    })
    // 是否显示标题
    const showTitle = computed(() => {
        return props?.portalConfiguration?.titleDisplay
    })
    // 标题样式
    const titleStyles = computed(() => {
        if (isEmpty(props.titleStyle.style)) {
            return {}
        }
        const { fontSize, color, bold, italic, underline, align } = props?.titleStyle?.style || {}
        return {
            fontSize: `${fontSize}px`,
            color,
            // @ts-ignore
            textAlign: alignType[align],
            fontWeight: bold ? 'bold' : 'normal',
            textDecoration: underline ? 'underline' : 'none',
            fontStyle: italic ? 'italic' : 'initial'
        }
    })
    const routerMap = computed(() => {
        const { children: otherRouterList } = pageRouter || { children: [] }
        let mainRouterList = []
        if (mainRouter && isArray(mainRouter)) {
            mainRouter.forEach(routerItem => {
                mainRouterList.push(...routerItem.children)
            })
        } else {
            mainRouterList = mainRouter.children
        }

        const otherRouterMap = {}
        const mainRouterMap = {}
        otherRouterList && recursiveSetRouterMap(otherRouterList, otherRouterMap)
        mainRouterList && recursiveSetRouterMap(mainRouterList, mainRouterMap)
        return {
            otherRouterMap,
            mainRouterMap
        }
    })
    // ----------------------------------------- 方法
    function recursiveSetRouterMap(routerList: any, resultMap: any) {
        routerList.forEach(item => {
            if (item.meta && item.meta.settingId) {
                resultMap[item.meta.settingId] = item.path
            }
            if (item.children && item.children.length > 0) {
                recursiveSetRouterMap(item.children, resultMap)
            }
        })
    }
    // 处理菜单高亮
    function handleDealMenuHightLight() {
        // 判断不同布局方式，因为有些布局，不需要打开，只选中即可
        const currentMenu = findMenu(props.menuList, routerPath)
        if (currentMenu) {
            const openkey = currentMenu.parentId !== '0' ? currentMenu.parentId : currentMenu.key
            defaultSelectedKeys.value = [currentMenu.key]
            activeTab.value = openkey
            if (props.layout !== 'horizontal') {
                menuExpandedKeys.value = [openkey]
            }
        }
    }
    // @ts-ignore
    function findMenu(data, menuUrl) {
        if (!menuUrl) {
            return
        }
        for (let index = 0; index < data.length; index++) {
            const currentData = data[index]
            if (currentData.menuUrl === menuUrl) {
                return currentData
            }
            let menu = null
            if (currentData?.children?.length) {
                menu = findMenu(currentData.children, menuUrl)
            }
            if (menu) {
                return menu
            }
        }
        return null
    }
    //  菜单项是否渲染
    function setMenuListByPermission(menuRaw, mixinRouterName = '') {
        if (!menuRaw || menuRaw.length === 0) {
            return []
        }
        const userStore = useUserStoreWithOut()
        const permissionCodeMap = userStore.getPermissionMap
        const menuList = []

        function recursiveRawMenu(_menuRaw, _menuList) {
            _menuRaw.forEach(item => {
                // 如果有权限
                if (item.code && permissionCodeMap?.includes(item.code)) {
                    const menuItem = Object.assign({}, item)
                    const { contentSetting } = item || { contentSetting: {} }
                    const { settingId } = contentSetting || {}
                    //DPA导航模式下，替换对应的路径
                    if (
                        mixinRouterName &&
                        routerMap.value[mixinRouterName] &&
                        settingId &&
                        routerMap.value[mixinRouterName][settingId]
                    ) {
                        menuItem.menuUrl = routerMap.value[mixinRouterName][settingId]
                    }
                    // 先将子菜单清空
                    menuItem.children = []
                    // 如果有子菜单
                    if (menuItem && item.children && item.children.length > 0) {
                        recursiveRawMenu(item.children, menuItem.children)
                    }
                    menuItem && _menuList.push(menuItem)
                }
            })
        }

        recursiveRawMenu(menuRaw, menuList)
        return menuList
    }
    // ----------------------------------------- 初始化
    onMounted(() => {
        handleDealMenuHightLight()
    })
    return {
        titleStyles,
        showTitle,
        computedHorizontalTheme,
        computedTheme,
        tabStyle,
        tabsStyle,
        collapsed,
        activeTab,
        Logo,
        menuExpandedKeys,
        defaultSelectedKeys,
        setMenuListByPermission
    }
}
export default useAlLayoutEffect
